﻿using System.Data.SqlClient;
using System.Data;

namespace Netnr.DataKit.DB
{
    /// <summary>
    /// SQLServer操作类
    /// </summary>
    public class SQLServerDB
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        public static string connectionString = string.Empty;

        /// <summary>
        /// 构造，初始化字符串
        /// </summary>
        /// <param name="conn"></param>
        public SQLServerDB(string conn = null)
        {
            if (conn != null)
            {
                connectionString = conn;
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="parameters">参数</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string sql, SqlParameter[] parameters = null)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, connection))
                {
                    if (parameters != null)
                    {
                        cmd.Parameters.AddRange(parameters);
                    }
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>DataTable</returns>
        public DataSet Query(string sql)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlDataAdapter sda = new SqlDataAdapter(sql, connection);
                DataSet ds = new DataSet();
                sda.Fill(ds, "ds");
                return ds;
            }
        }
    }
}